package com.wxl.xueyuan.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.wxl.xueyuan.MyApp;
import com.wxl.xueyuan.R;
import com.wxl.xueyuan.activity.DownloadActivity;
import com.wxl.xueyuan.activity.LoginActivity;
import com.wxl.xueyuan.activity.LoginfoActivity;
import com.wxl.xueyuan.activity.SettingActivity;
import com.wxl.xueyuan.activity.VisitActivity;
import com.wxl.xueyuan.api.Api;
import com.wxl.xueyuan.api.ApiConfig;
import com.wxl.xueyuan.api.MCallback;
import com.wxl.xueyuan.util.ActivityCollectorUtil;
import com.wxl.xueyuan.view.CircleTransform;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MyFragment extends BaseFragment {
    private static final int COMPLETED = 0;
    private ImageView ivHead;//头像显示
    private Button btnTakephoto;//拍照
    private Button btnPhotos;//相册
    private Bitmap head;//头像Bitmap
    private static String path = "/sdcard/DemoHead/";//sd路径
    private View download;
    private View loginfo;
    private View logout;
    private View record;
    private View set;
    private TextView name;
    private TextView intro;
    @BindView(R.id.img_header)
    ImageView imgHeader;

    public MyFragment() {
    }

    public static MyFragment newInstance() {
        MyFragment fragment = new MyFragment();
        return fragment;
    }

    @Override
    protected int initLayout() {
        Api.accessImageAndFile();
        return R.layout.fragment_my;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View square = inflater.inflate(R.layout.fragment_my, container, false);
        name = square.findViewById(R.id.name);
        intro = square.findViewById(R.id.intro);
        logout = square.findViewById(R.id.rl_logout);
        download = square.findViewById(R.id.rl_download);
        loginfo = square.findViewById(R.id.rl_loginfo);
        set = square.findViewById(R.id.rl_set);
        record = square.findViewById(R.id.rl_record);
        ivHead = square.findViewById(R.id.img_header);
        System.out.println(ivHead);
        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像，转换成Bitmap

        System.out.println("没有头像");
        if (bt != null) {
            //如果本地有头像图片的话
            System.out.println("有头像");
            CircleTransform c = new CircleTransform();
            bt = c.transform(bt);
            ivHead.setImageBitmap(bt);
        }
        HashMap params = new HashMap();
        params.put("ID", MyApp.getmData("ID"));
        Api.config("/user/name", params).getRequest(getActivity(), new MCallback() {
            @Override
            public void onSuccess(String res) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("name:"+res);
                        name.setText(res);
                    }
                });
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
        Api.config("/user/intro", params).getRequest(getActivity(), new MCallback() {
            @Override
            public void onSuccess(String res) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("intro:"+res);
                        intro.setText(res);
                    }
                });
            }

            @Override
            public void onFailure(Exception e) {

            }
        });

        return square;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);//返回被选中项的URI
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");//得到所有图片的URI
//                System.out.println("MediaStore.Images.Media.EXTERNAL_CONTENT_URI  ------------>   "
//                        + MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//   content://media/external/images/media
                startActivityForResult(intent1, 1);
            }
        });
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("下载记录");
                navigateTo(DownloadActivity.class);
            }
        });
        loginfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("登录信息");
                navigateTo(LoginfoActivity.class);
            }
        });
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("退出");
                navigateTo(LoginActivity.class);
                ActivityCollectorUtil.finishAllActivity();
            }
        });
        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("浏览记录");
                navigateTo(VisitActivity.class);
            }
        });
        set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("设置");
                Bundle bundle = new Bundle();
                bundle.putString("etint", intro.getText().toString());
                bundle.putString("etname", name.getText().toString());
                navigateToWithBundle(SettingActivity.class, bundle);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //从相册里面取相片的返回结果
            case 1:
                if (resultCode == -1) {
                    cropPhoto(data.getData());//裁剪图片
                }

                break;
            //相机拍照后的返回结果
            case 2:


                break;
            //调用系统裁剪图片后
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);//保存在SD卡中
                        CircleTransform c = new CircleTransform();
                        head = c.transform(head);
                        ivHead.setImageBitmap(head);//用ImageView显示出来
                    }
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    ;

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //找到指定URI对应的资源图片
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        //进入系统裁剪图片的界面
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd卡是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建以此File对象为名（path）的文件夹
        String fileName = path + "head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件（compress：压缩）
            okHttpUploadImage(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void okHttpUploadImage(String filename) {
        System.out.println("开始");
        // 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient();
        // 要上传的文件
        File file = new File(filename);
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType((MultipartBody.FORM));
        // 把文件封装进请求体
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
        System.out.println(file.getName());
        // 设置图片名
        String fileName = MyApp.getmData("ID") + ".jpg";
        requestBody.addFormDataPart("file", fileName, fileBody);

        final Request request = new Request.Builder().
                url(ApiConfig.BASE_URl + "/user/upload").
                post(requestBody.build()).
                build();
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("文件上传", "失败了");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Log.d("上传文件成功", jsonObject.getString("code"));
                        Log.d("服务器上的文件名", jsonObject.getString("body"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.d("文件上传", response.message() + "error:body" + response.body().string());
                }
            }
        });

    }
}